#include "mapcache.h"

MapCache::MapCache(int cache_size)
{
    this->cache_size = cache_size;
    this->node_count = 0;
    this->first_list_node = NULL;
}

MapCache::~MapCache()
{
    clear();
}

void MapCache::deleteNode(ListNode* node)
{
    if(node->next != NULL) {
        deleteNode(node->next);
    }
    delete node->ele;
    delete node;
}

void MapCache::push(int layer, int x, int y)
{
    ListNode* push_node = new ListNode;
    push_node->ele = new ElementMap(layer, x, y);
    push_node->next = first_list_node;
    connect(push_node->ele,&ElementMap::map_update,this,&MapCache::map_update);
    first_list_node = push_node;
    if(node_count <= cache_size) node_count++;
    else {
        ListNode* temp;
        for(temp = first_list_node; temp->next->next != NULL; temp = temp->next) continue;
        deleteNode(temp->next);
        temp->next = NULL;
    }
}

bool MapCache::find(int layer, int x, int y)
{
    ListNode* now_node = first_list_node;
    ListNode** last_node_next = &first_list_node;
    while(now_node != NULL) {
        if(now_node->ele->isEqual(layer, x, y)) {
            *last_node_next = now_node->next;
            now_node->next = first_list_node;
            first_list_node = now_node;
            return true;
        }
        if(now_node->next == NULL) break;
        last_node_next = &now_node->next;
        now_node = now_node->next;
    }
    return false;
}

const QPixmap& MapCache::get()
{
    return first_list_node->ele->getMap();
}

void MapCache::clear()
{
    if(first_list_node != NULL){
        deleteNode(first_list_node);
        first_list_node = NULL;
        node_count = 0;
    }
}
